<script>
import { keyMap } from './index'
import { getSearchFields } from '@/api/basic'

import Field from './field.vue'

export default {
  components: {
    Field
  },
  props: {
    value: {
      type: Object,
      required: true,
      default: {}
    }
  },
  data() {
    return {
      // form:{},
      keyMap,
      fields: [],
      availableFields: [],
      blackLit: ['name']
    }
  },
  computed: {
    form: {
      get() {
        return this.value
      },
      set(v) {
        this.$emit('input', v)
      }
    },
    availableFieldsFormatted() {
      return this.availableFields.map(item => {
        const { table, field, type, name, id } = item
        return {
          id,
          field,
          label: name,
          fieldType: type,
          ofTable: table,
          placeholder: this.genPlacholderText(type, name)
        }
      }).filter(item => !this.blackLit.includes(item.field))
    },
    options() {
      return this
        .availableFieldsFormatted
        .map(item => {
          return {
            id: item.id,
            label: item.label,
            value: {
              ...item,
              value: item.field
            }
          }
        })
    },
    fieldsMap() {
      const fields = new Map()
      for (const field of this.availableFieldsFormatted) {
        fields.set(field.field, field)
      }
      return fields
    }
  },
  watch: {
    form: {
      handler(v) {
        console.log(v)
      },
      deep: true
    }
  },
  created() {
    this.initData()
  },
  methods: {
    getPlaceholder(field) {
      return this.fieldsMap.get(field)?.placeholder ?? ''
    },
    getLabel(field) {
      return this.fieldsMap.get(field)?.label ?? ''
    },
    async initData() {
      try {
        await this.loadData()
      } catch (e) {
        console.log(e)
      }
    },
    async loadData() {
      await Promise.allSettled([
        this.getAvailableConditionFields()
      ])
    },
    async getAvailableConditionFields() {
      const params = {
        table: JSON.stringify(['user_details'])
      }
      const result = await getSearchFields(params)
      if (result.code !== 200) { throw new Error(result.message) }
      this.availableFields = result.data
    },
    genPlacholderText(fieldType, label) {
      switch (fieldType) {
        case 'string':
          return `请填写${label}`

        case 'number':
          return `请填写${label}`

        case 'date':
          return `请选择${label}`
      }
      return `请填写${label}`
    },
    saveFields() {
      if (this.fields.length <= 0) {
        // return this.$message.error('请选择字段')
        this.form = []
        return
      }
      const form = {}
      const values = this.fields.values()
      for (const field of values) {
        const f = {
          id: field.id,
          field: field.field,
          ofTable: field.ofTable
        }
        switch (field.fieldType) {
          case 'string':
            f['search'] = ''
            break
          case 'number':
            f['search'] = null
            break
          case 'date':
            f['search'] = null
            break
        }
        form[field.field] = f
      }
      for (const k in form) {
        if (k in this.form) {
          form[k] = this.form[k]
        }
      }
      this.form = form
    }
  }
}
</script>

<template>
  <el-form
    inline
    :model="form"
  >
    <slot name="extra" />
    <el-form-item
      v-for="(value,field) in form"
      :key="field"
      :prop="field"
      :label="getLabel(field)"
    >
      <Field v-model="form[field].search" :field="fieldsMap.get(field)" :placeholder="getPlaceholder(field)" />
    </el-form-item>

    <el-form-item>
      <div class="warp">
        <el-select
          v-model="fields"
          multiple
          placeholder="请输入关键字搜索搜索条件"
          filterable
          size="medium"
          style="width: 100%;flex: 1;padding-right: 10px;"
          collapse-tags
        >
          <el-option
            v-for="option in options"
            :key="option.value.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>

        <el-button size="medium" @click="saveFields">保存</el-button>
        <el-button type="primary" size="medium" @click="$emit('search')">查询</el-button>
      </div>
    </el-form-item>

  </el-form>
</template>

<style lang="scss" scoped>
    .warp {
        display: flex;
        justify-content: space-between;
        align-items: center;

    }
</style>
